package acs.http;

import acs.offer.collection.Params;
import acs.offer.constant.Constant;
import acs.offer.constant.EventType;
import acs.offer.util.DMSSoftTimer;
import acs.offer.util.ServerCache;

import java.util.*;

/**
 * ���ݿ⹤��
 * @author Administrator
 *
 */
public class DbUtil {
	List<Params> paramsList=new ArrayList<>();
	private volatile boolean  isUpdate=false;
	private static DbUtil instance =new DbUtil();
	public static DbUtil getInstance() {
		return instance;
	}

	String key="xiao";
	public Map<String, Object> loadOffer(Params params){
		while(isUpdate) {}//让第二个线程等待
		paramsList.add(params);
		Map<String,String>  map=params.get(Constant.REQUEST_PARAMS);
		String requestType=params.get(Constant.REQUEST_TYPE);
		String cacheKey = requestType+":"+map.toString();
		Map<String, String> offers = ServerCache.getInstance().get(cacheKey);
		if(offers == null) {
			System.out.println("根据参数去数据库加载数据");
			ServerCache.getInstance().put(cacheKey,Collections.emptyMap());//放入一个空结果，第二个相同请求就会走下面那个条件
			offers = loadOffer(requestType,map);
			ServerCache.getInstance().put(cacheKey,offers);//加入缓存
		}else if(offers.isEmpty()){
			//说明第二次请求和第一次是一样的，第一次请求的数据还没返回
		}
		DMSSoftTimer.getInstance().startTimer(100*1000, EventType.TIMEOUT_FOR_CACHE_OFFER,params);//开始清除缓存倒计时
		
		this.notifyInstance(offers);
	    System.out.println("服务端查到了offer，现在开始给客户端返回offer信息");
		return null;
	}

	private void notifyInstance(Map<String, String> offers ) {
		this.isUpdate=true;
		Iterator<Params> iterator = paramsList.iterator();
		while(iterator.hasNext()) {
			Params params = iterator.next();
			params.put(Constant.RESPONSE_DATA, offers);
		    EventBus.getInstance().putMessage(EventType.RESPONSE_FOR_DATA, params);
			iterator.remove();
		}
		this.isUpdate=false;
	}
	
	private Map<String, String> loadOffer(String requestType,Map<String,String>  param){
		Map<String,String>  result=new HashMap<>();
		for(Map.Entry<String,String> entry : param.entrySet()) {
			result.put(requestType+":"+entry.getKey(), entry.getValue());
		}
		return result;

	}

}
